# -*- coding: utf-8 -*-
# @Author : zhaochen
# @Date   : 2019/2/19
# @File   : R16_IC_AccOvduCntOfLoansAndCreditAndQuasiSixMonsCheck.py
# @E-mail : zhaochen@bbdservice.com

'''eof
name:申请人近6个月内贷款、贷记卡及准贷记卡累计逾期次数校验
code:R16_IC_AccOvduCntOfLoansAndCreditAndQuasiSixMonsCheck_2D
tableName:
columnName:
groups:个人征信校验
dependencies:IC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''

import sys
import re
import datetime
import pandas as pd
reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

def getTable(data, tableName, occurTimes, iteratorTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :param iteratorTimes:下级字段出现的次数，如果是0代表下级字段可以不出现，如果是1代表下级字段必须出现
        :return:该表全部数据  返回[{}]为异常缺失，返回0为正常缺失，其他返回正常数组
        '''
    try:
        table = data.get(tableName)
        if occurTimes == 0:
            if table is None or (table == "" and iteratorTimes == 0):
                return 0
            elif isinstance(table, list) is False or len(table) == 0 or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
        if occurTimes == 1:
            if table == "" and iteratorTimes == 0:
                return 0
            if table is None or isinstance(table, list) is False or len(table) == 0 \
                    or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
    except:
        return [{}]


def getCount(statusList, min, max, endMonth=None, type=1, deltaMonth=6):
    # print(statusList)
    if statusList in null_type_list:
        return -1
    if type == 1:
        stateStr = 'PD01DD01'  # 24个月还款状态
        monthStr = 'PD01DR03'  # 月份
    else:
        stateStr = 'PD01ED01'  # 五年的还款状态
        monthStr = 'PD01ER03'  # 月份
    if endMonth is None:
        # 使用当前时间为阈值
        endMonthStr = datetime.datetime.now().strftime("%Y-%m-%d")
        endMonthFact = float(endMonthStr[:4]) * 12 + float(endMonthStr[5:7])
    else:
        try:
            # 使用传入的截止日期计算阈值
            endMonthFact = float(endMonth[:4]) * 12 + float(endMonth[5:7]) if len(endMonth) >= 6 else None
            if endMonthFact is None:
                return -1
        except:
            return -1
    monthsAgo = endMonthFact - deltaMonth
    # result = [] # 返回数字的state的list
    flag = False
    result = []
    for i in statusList:
        try:
            state = i.get(stateStr)
            month = i.get(monthStr)
            monthFact = float(month[:4]) * 12 + float(month[5:7])
            if state not in null_type_list:
                flag = True
            if ((isfloat(state) and min <= int(state) <= max)) and  (monthFact > monthsAgo and monthFact <= endMonthFact):
                # 存值
                result.append(int(state))
        except:
            continue
    if flag:
        if len(result) != 0:
            return result
        else:
            return -1
    else:
        return -1

def checkNull(data,PD01BD01,accountType):
    '''若最近24个月还款状态信息为空，返回结果为缺失值，则进行以下逻辑判断：
1.基本信息段（PD01A）-账户类型（PD01AD01）为D1，若最新表现信息段（PD01B）-账户状态（PD01BD01）为3（结清）且关闭日期（PD01BR01）＞5年或账户状态（PD01BD01）为5（转出）且转出月份（PD01BR04）＞5年，则Factor=1,否则Factor=缺失值；
2.基本信息段（PD01A）-账户类型（PD01AD01）为R1,R4，若最新表现信息段（PD01B）-账户状态（PD01BD01）为3（结清）且关闭日期（PD01BR01）＞5年，则Factor=1,否则Factor=缺失值；
3.基本信息段（PD01A）-账户类型（PD01AD01）为R2，R3，若最新表现信息段（PD01B）-账户状态（PD01BD01）为4(销户)且关闭日期（PD01BR01）＞5年或账户状态（PD01BD01）为6(未激活)，则Factor=1,否则Factor=缺失值；'''
    if data in null_type_list or data == [{}] or data == 0:
        return 0
    # 账户状态
    #PD01BD01 = data[0].get("PD01BD01")
    # 关闭日期
    PD01BR01 = data[0].get("PD01BR01")
    PD01BR01 = dateFormat(PD01BR01)
    # 转出月份
    PD01BR04 = data[0].get("PD01BR04")
    PD01BR04 = dateFormat(PD01BR04)
    fiveYearsAgo = (datetime.datetime.now() - pd.tseries.offsets.DateOffset(years=5)).strftime("%Y%m")
    if accountType == "D1":
        if (PD01BD01 == "3" and PD01BR01 is not None and PD01BR01.strftime("%Y%m") <= fiveYearsAgo)\
                or (PD01BD01 == "5" and PD01BR04 is not None and PD01BR04.strftime("%Y%m") <= fiveYearsAgo):
            return 1
        else:
            return 0
    elif accountType in ["R1", "R4"]:
        if (PD01BD01 == "3" and PD01BR01 is not None and PD01BR01.strftime("%Y%m") <= fiveYearsAgo):
            return 1
        else:
            return 0
    elif accountType in ["R2", "R3"]:
        if (PD01BD01 == "4" and PD01BR01 is not None and PD01BR01.strftime("%Y%m") <= fiveYearsAgo) \
                or (PD01BD01 == "6"):
            return 1
        else:
            return 0
    else:
        return 0

def dateFormat(time):
    import re
    import datetime
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d')
                except:
                    date = None
    return date

def isfloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x)>=0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False

# 计算24个月记录和5年逾期记录
# def R16_IC_AccOvduCntOfLoansAndCreditAndQuasiSixMonsCheck():
#     data = IC_DSJ_2D['data']
#     # 借贷账户信息
#     PDA = getTable(data, 'PDA', 1, 0)
#     if PDA == [{}]:
#         return u'缺失值'
#     elif PDA == 0:
#         return 1
#     else:
#         # 借贷账户信息单元 PD01[0.*]
#         PD01 = getTable(PDA[0], 'PD01', 0, 1)
#         if PD01 == [{}]:
#             return u'缺失值'
#         elif PD01 == 0:
#             return 1
#         else:
#             factor = []
#             for i in PD01:
#                 try:
#                     # 基本信息段 PD01A[1.1]
#                     PD01A = getTable(i, 'PD01A', 1, 1)
#                     if PD01A == [{}]:
#                         factor.append(None)
#                     elif PD01A == 0:
#                         factor.append(0)
#                     else:
#                         # 账号类型
#                         PD01AD01 = PD01A[0].get("PD01AD01")
#                         if PD01AD01 not in null_type_list:
#                             if PD01AD01 in ['D1', 'R1', 'R2', 'R4']:
#                                 # 最近24个月还款状态信息段 PD01D[0.1]
#                                 PD01D = getTable(i, 'PD01D', 0, 1)
#                                 if not (PD01D == [{}] or PD01D == 0):
#                                     PD01D = PD01D[0]
#                                     # 获取24位状态码列表
#                                     PD01DH = PD01D.get("PD01DH")
#                                     # 24个月的截止日期
#                                     PD01DR02 = PD01D.get("PD01DR02")
#                                     stateList = getCount(PD01DH, min=1, max=7, endMonth=PD01DR02, type=1, deltaMonth=6)
#                                     if stateList == -1:
#                                         factor.append(None)
#                                     else:
#                                         factor.extend(stateList)
#                                 else:
#                                     # 最新表现信息段  PD01B  [1..1]
#                                     PD01B = getTable(i, 'PD01B', 1, 1)
#                                     # 最近一次月度表现信息段
#                                     PD01C = getTable(i, 'PD01C', 1, 1)
#                                     # 最近5年内的历史表现信息段
#                                     PD01E = getTable(i, 'PD01E', 0, 1)
#                                     if PD01E == [{}] or PD01B == [{}]:
#                                         factor.append(None)
#                                     elif PD01E == 0:
#                                         factor.append(0)
#                                     else:
#                                         # 截止年月：
#                                         PD01ER02 = PD01E[0].get('PD01ER02')
#                                         # 历史表现信息 PD01EH
#                                         PD01EH = PD01E[0].get('PD01EH')
#                                         # 账户状态
#                                         PD01BD01 = PD01B[0].get('PD01BD01')
#                                         PD01CD01 = PD01C[0].get('PD01CD01')
#                                         if PD01BD01 in null_type_list:
#                                             PD01BD01 = PD01CD01
#                                             if PD01BD01 in null_type_list:
#                                                 factor.append(None)
#                                             else:
#                                                 if PD01BD01 in ['1', '2']:
#                                                     # 未结清使用截止日期判断
#                                                     stateList = getCount(PD01EH, min=1, max=7, endMonth=PD01ER02, type=2,
#                                                                      deltaMonth=6)
#                                                 else:
#                                                     # 已结清使用当前时间判断
#                                                     stateList = getCount(PD01EH, min=1, max=7, endMonth=None, type=2,
#                                                                      deltaMonth=6)
#                                                 if stateList == -1:
#                                                     # 检查是否为5年之外结清或者转出的情况
#                                                     checkRes = checkNull(PD01B,PD01BD01,accountType=PD01AD01)
#                                                     if checkRes:
#                                                         factor.append(0)
#                                                     else:
#                                                         factor.append("None")
#                                                 else:
#                                                     factor.extend(stateList)
#                                         else:
#                                             if PD01BD01 in ['1', '2']:
#                                                 # 未结清使用截止日期判断
#                                                 stateList = getCount(PD01EH, min=1, max=7, endMonth=PD01ER02, type=2,
#                                                                      deltaMonth=6)
#                                             else:
#                                                 # 已结清使用当前时间判断
#                                                 stateList = getCount(PD01EH, min=1, max=7, endMonth=None, type=2,
#                                                                      deltaMonth=6)
#                                             if stateList == -1:
#                                                 # 检查是否为5年之外结清或者转出的情况
#                                                 checkRes = checkNull(PD01B,PD01BD01,accountType=PD01AD01)
#                                                 if checkRes:
#                                                     factor.append(0)
#                                                 else:
#                                                     factor.append("None")
#                                             else:
#                                                 factor.extend(stateList)
#                             elif PD01AD01 == "R3":
#                                 # 最近24个月还款状态信息段 PD01D[0.1]
#                                 PD01D = getTable(i, 'PD01D', 0, 1)
#                                 if not (PD01D == [{}] or PD01D == 0):
#                                     PD01D = PD01D[0]
#                                     # 24个月的截止日期
#                                     PD01DR02 = PD01D.get("PD01DR02")
#                                     # 获取24位状态码列表
#                                     PD01DH = PD01D.get("PD01DH")
#                                     stateList = getCount(PD01DH, min=3, max=7, endMonth=PD01DR02, type=1, deltaMonth=6)
#                                     if stateList == -1:
#                                         factor.append(None)
#                                     else:
#                                         factor.extend(stateList)
#                                 else:
#                                     # 最新表现信息段  PD01B  [1..1]
#                                     PD01B = getTable(i, 'PD01B', 1, 1)
#                                     # 最近一次月度表现信息段
#                                     PD01C = getTable(i, 'PD01C', 1, 1)
#                                     # 最近 5 年内的历史表现信息段
#                                     PD01E = getTable(i, 'PD01E', 0, 1)
#                                     if PD01E == [{}] or PD01B == [{}]:
#                                         factor.append(None)
#                                     elif PD01E == 0 or PD01B == 0:
#                                         factor.append(0)
#                                     else:
#                                         # 截止年月：
#                                         PD01ER02 = PD01E[0].get('PD01ER02')
#                                         # 历史表现信息 PD01EH
#                                         PD01EH = PD01E[0].get('PD01EH')
#                                         # 账户状态
#                                         PD01BD01 = PD01B[0].get('PD01BD01')
#                                         PD01CD01 = PD01C[0].get('PD01CD01')
#                                         if PD01BD01 in null_type_list:
#                                             PD01BD01 = PD01CD01
#                                             if PD01BD01 in null_type_list:
#                                                 factor.append(None)
#                                             else:
#                                                 if PD01BD01 in ['1', '2']:
#                                                     # 未结清使用截止日期判断
#                                                     stateList = getCount(PD01EH, min=3, max=7, endMonth=PD01ER02, type=2,
#                                                                          deltaMonth=6)
#                                                 else:
#                                                     # 已结清使用当前时间判断
#                                                     stateList = getCount(PD01EH, min=3, max=7, endMonth=None, type=2,
#                                                                      deltaMonth=6)
#                                                 if stateList == -1:
#                                                     # 检查是否为5年之外结清或者转出的情况
#                                                     checkRes = checkNull(PD01B,PD01BD01,accountType=PD01AD01)
#                                                     if checkRes:
#                                                         factor.append(0)
#                                                     else:
#                                                         factor.append("None")
#                                                 else:
#                                                     factor.extend(stateList)
#                                         else:
#                                             if PD01BD01 in ['1', '2']:
#                                                 # 未结清使用截止日期判断
#                                                 stateList = getCount(PD01EH, min=3, max=7, endMonth=PD01ER02, type=2,
#                                                                      deltaMonth=6)
#                                             else:
#                                                 # 已结清使用当前时间判断
#                                                 stateList = getCount(PD01EH, min=3, max=7, endMonth=None, type=2,
#                                                                      deltaMonth=6)
#                                             if stateList == -1:
#                                                 # 检查是否为5年之外结清或者转出的情况
#                                                 checkRes = checkNull(PD01B,PD01BD01,accountType=PD01AD01)
#                                                 if checkRes:
#                                                     factor.append(0)
#                                                 else:
#                                                     factor.append("None")
#                                             else:
#                                                 factor.extend(stateList)
#                             else:
#                                 factor.append(0)
#                         else:
#                             factor.append(None)
#                 except:
#                     factor.append(None)
#                     continue
#     if "None" in factor:
#         return u'缺失值'
#     factorNotNone = filter(lambda x: x is not None, factor)
#     factorNotNoneNotZero = filter(lambda x: x != 0, factorNotNone)
#     if len(factorNotNone) == 0:
#         return u'缺失值'
#     elif len(factorNotNoneNotZero) == 0:
#         return 1
#     elif len(factorNotNoneNotZero) > 3 or max(factorNotNoneNotZero) > 1:
#         return 0
#     else:
#         return 1

# 仅使用5年逾期记录计算
def R16_IC_AccOvduCntOfLoansAndCreditAndQuasiSixMonsCheck2():
    data = IC_DSJ_2D['data']
    # 借贷账户信息
    PDA = getTable(data, 'PDA', 1, 0)
    if PDA == [{}]:
        return u'缺失值'
    elif PDA == 0:
        return 1
    else:
        # 借贷账户信息单元 PD01[0.*]
        PD01 = getTable(PDA[0], 'PD01', 0, 1)
        if PD01 == [{}]:
            return u'缺失值'
        elif PD01 == 0:
            return 1
        else:
            factor1 = []
            factor2 = []
            for i in PD01:
                try:
                    # 基本信息段 PD01A[1.1]
                    PD01A = getTable(i, 'PD01A', 1, 1)
                    if PD01A == [{}] or PD01A == 0:
                        continue
                    #     factor.append(None)
                    # elif PD01A == 0:
                    #     factor.append(0)
                    else:
                        # 账号类型
                        PD01AD01 = PD01A[0].get("PD01AD01")
                        if PD01AD01 not in null_type_list:
                            flag = True
                            if PD01AD01 in ['D1', 'R1', 'R2', 'R4']:
                                # 最新表现信息段  PD01B  [1..1]
                                PD01B = getTable(i, 'PD01B', 1, 1)
                                # 最近一次月度表现信息段
                                PD01C = getTable(i, 'PD01C', 1, 1)
                                # 最近5年内的历史表现信息段
                                PD01E = getTable(i, 'PD01E', 0, 1)
                                if PD01E == [{}] or PD01B == [{}]:
                                    factor1.append(None)
                                elif PD01E == 0:
                                    factor1.append(0)
                                else:
                                    # 截止年月：
                                    PD01ER02 = PD01E[0].get('PD01ER02')
                                    # 历史表现信息 PD01EH
                                    PD01EH = PD01E[0].get('PD01EH')
                                    #新增逻辑
                                    # 信息报告日期
                                    PD01CR04 = PD01C[0].get('PD01CR04')
                                    if PD01EH in null_type_list or len(PD01EH) == 0:
                                        PRH = getTable(data, 'PRH', 1, 1)
                                        PA01 = getTable(PRH[0], 'PA01', 1, 1)
                                        PA01A = getTable(PA01[0], 'PA01A', 1, 1)
                                        PA01AR01 = PA01A[0].get('PA01AR01')
                                        if PA01AR01 not in null_type_list and PD01CR04 not in null_type_list:
                                            if dateFormat(PD01CR04) in null_type_list or dateFormat(PA01AR01.split('T')[0]) in null_type_list:
                                                flag = False
                                                # factor1.append("None")
                                            else:
                                                if int(dateFormat(PD01CR04).strftime("%Y%m")) < int((dateFormat(PA01AR01.split('T')[0]) - pd.tseries.offsets.DateOffset(years=5)).strftime("%Y%m")):
                                                    factor1.append(0)
                                                else:
                                                    flag = False
                                        else:
                                            flag = False
                                            # factor1.append("None")
                                            # continue
                                    else:
                                    # 账户状态
                                        PD01BD01 = PD01B[0].get('PD01BD01')
                                        PD01CD01 = PD01C[0].get('PD01CD01')
                                        if PD01BD01 in null_type_list:
                                            PD01BD01 = PD01CD01
                                            if PD01BD01 in null_type_list:
                                                factor1.append(None)
                                            else:
                                                if PD01BD01 in ['1', '2']:
                                                    # 未结清使用截止日期判断
                                                    stateList = getCount(PD01EH, min=1, max=7, endMonth=PD01ER02, type=2,
                                                                         deltaMonth=6)
                                                else:
                                                    # 已结清使用当前时间判断
                                                    stateList = getCount(PD01EH, min=1, max=7, endMonth=None, type=2,
                                                                     deltaMonth=6)
                                                if stateList == -1:
                                                    factor1.append(0)
                                                else:
                                                    factor1.extend(stateList)
                                        else:
                                            if PD01BD01 in ['1', '2']:
                                                # 未结清使用截止日期判断
                                                stateList = getCount(PD01EH, min=1, max=7, endMonth=PD01ER02, type=2,
                                                                     deltaMonth=6)
                                            else:
                                                # 已结清使用当前时间判断
                                                stateList = getCount(PD01EH, min=1, max=7, endMonth=None, type=2,
                                                                     deltaMonth=6)
                                            if stateList == -1:
                                                factor1.append(0)
                                            else:
                                                factor1.extend(stateList)

                                if flag == False:
                                    PD01BD01 = PD01B[0].get('PD01BD01')
                                    PD01CD01 = PD01C[0].get('PD01CD01')
                                    if PD01BD01 in null_type_list:
                                        PD01BD01 = PD01CD01
                                        if PD01BD01 in null_type_list:
                                            factor1.append(None)
                                        else:
                                            if PD01BD01 in ['1', '2']:
                                                # 未结清使用截止日期判断
                                                stateList = getCount(PD01EH, min=1, max=7, endMonth=PD01ER02, type=2,
                                                                     deltaMonth=6)
                                            else:
                                                # 已结清使用当前时间判断
                                                stateList = getCount(PD01EH, min=1, max=7, endMonth=None, type=2,
                                                                 deltaMonth=6)
                                            if stateList == -1:
                                                # 检查是否为5年之外结清或者转出的情况
                                                checkRes = checkNull(PD01B,PD01BD01,accountType=PD01AD01)
                                                if checkRes:
                                                    factor1.append(0)
                                                else:
                                                    factor1.append("None")
                                            else:
                                                factor1.extend(stateList)
                                    else:
                                        if PD01BD01 in ['1', '2']:
                                            # 未结清使用截止日期判断
                                            stateList = getCount(PD01EH, min=1, max=7, endMonth=PD01ER02, type=2,
                                                                 deltaMonth=6)
                                        else:
                                            # 已结清使用当前时间判断
                                            stateList = getCount(PD01EH, min=1, max=7, endMonth=None, type=2,
                                                                 deltaMonth=6)
                                        if stateList == -1:
                                            # 检查是否为5年之外结清或者转出的情况
                                            checkRes = checkNull(PD01B,PD01BD01,accountType=PD01AD01)
                                            if checkRes:
                                                factor1.append(0)
                                            else:
                                                factor1.append("None")
                                        else:
                                            factor1.extend(stateList)

                            elif PD01AD01 == "R3":
                                # 最新表现信息段  PD01B  [1..1]
                                PD01B = getTable(i, 'PD01B', 1, 1)
                                # 最近一次月度表现信息段
                                PD01C = getTable(i, 'PD01C', 1, 1)
                                # 最近 5 年内的历史表现信息段
                                PD01E = getTable(i, 'PD01E', 0, 1)
                                if PD01E == [{}] or PD01B == [{}]:
                                    factor2.append(None)
                                elif PD01E == 0 or PD01B == 0:
                                    factor2.append(0)
                                else:
                                    # 截止年月：
                                    PD01ER02 = PD01E[0].get('PD01ER02')
                                    # 历史表现信息 PD01EH
                                    PD01EH = PD01E[0].get('PD01EH')
                                    #新增逻辑
                                    # 信息报告日期
                                    PD01CR04 = PD01C[0].get('PD01CR04')
                                    if PD01EH in null_type_list or len(PD01EH) == 0:
                                        PRH = getTable(data, 'PRH', 1, 1)
                                        PA01 = getTable(PRH[0], 'PA01', 1, 1)
                                        PA01A = getTable(PA01[0], 'PA01A', 1, 1)
                                        PA01AR01 = PA01A[0].get('PA01AR01')
                                        if PA01AR01 not in null_type_list and PD01CR04 not in null_type_list:
                                            if dateFormat(PD01CR04) in null_type_list or dateFormat(PA01AR01.split('T')[0]) in null_type_list:
                                                flag = False
                                                # factor1.append("None")
                                            else:
                                                if int(dateFormat(PD01CR04).strftime("%Y%m")) < int((dateFormat(PA01AR01.split('T')[0]) - pd.tseries.offsets.DateOffset(years=5)).strftime("%Y%m")):
                                                    factor2.append(0)
                                                else:
                                                    flag = False
                                        else:
                                            flag = False
                                            # factor2.append("None")
                                            # continue
                                    else:
                                    # 账户状态
                                        PD01BD01 = PD01B[0].get('PD01BD01')
                                        PD01CD01 = PD01C[0].get('PD01CD01')
                                        if PD01BD01 in null_type_list:
                                            PD01BD01 = PD01CD01
                                            if PD01BD01 in null_type_list:
                                                factor2.append(None)
                                            else:
                                                if PD01BD01 in ['1', '2']:
                                                    # 未结清使用截止日期判断
                                                    stateList = getCount(PD01EH, min=3, max=7, endMonth=PD01ER02, type=2,
                                                                     deltaMonth=6)
                                                else:
                                                    # 已结清使用当前时间判断
                                                    stateList = getCount(PD01EH, min=3, max=7, endMonth=None, type=2,
                                                                     deltaMonth=6)
                                                if stateList == -1:
                                                    factor2.append(0)
                                                else:
                                                    factor2.extend(stateList)
                                        else:
                                            if PD01BD01 in ['1', '2']:
                                                # 未结清使用截止日期判断
                                                stateList = getCount(PD01EH, min=3, max=7, endMonth=PD01ER02, type=2,
                                                                     deltaMonth=6)
                                            else:
                                                # 已结清使用当前时间判断
                                                stateList = getCount(PD01EH, min=3, max=7, endMonth=None, type=2,
                                                                     deltaMonth=6)
                                            if stateList == -1:
                                                factor2.append(0)
                                            else:
                                                factor2.extend(stateList)
                                if flag == False:
                                    PD01BD01 = PD01B[0].get('PD01BD01')
                                    PD01CD01 = PD01C[0].get('PD01CD01')
                                    if PD01BD01 in null_type_list:
                                        PD01BD01 = PD01CD01
                                        if PD01BD01 in null_type_list:
                                            factor2.append(None)
                                        else:
                                            if PD01BD01 in ['1', '2']:
                                                # 未结清使用截止日期判断
                                                stateList = getCount(PD01EH, min=1, max=7, endMonth=PD01ER02, type=2,
                                                                     deltaMonth=6)
                                            else:
                                                # 已结清使用当前时间判断
                                                stateList = getCount(PD01EH, min=1, max=7, endMonth=None, type=2,
                                                                 deltaMonth=6)
                                            if stateList == -1:
                                                # 检查是否为5年之外结清或者转出的情况
                                                checkRes = checkNull(PD01B,PD01BD01,accountType=PD01AD01)
                                                if checkRes:
                                                    factor2.append(0)
                                                else:
                                                    factor2.append("None")
                                            else:
                                                factor2.extend(stateList)
                                    else:
                                        if PD01BD01 in ['1', '2']:
                                            # 未结清使用截止日期判断
                                            stateList = getCount(PD01EH, min=1, max=7, endMonth=PD01ER02, type=2,
                                                                 deltaMonth=6)
                                        else:
                                            # 已结清使用当前时间判断
                                            stateList = getCount(PD01EH, min=1, max=7, endMonth=None, type=2,
                                                                 deltaMonth=6)
                                        if stateList == -1:
                                            # 检查是否为5年之外结清或者转出的情况
                                            checkRes = checkNull(PD01B,PD01BD01,accountType=PD01AD01)
                                            if checkRes:
                                                factor2.append(0)
                                            else:
                                                factor2.append("None")
                                        else:
                                            factor2.extend(stateList)
                            else:
                                continue
                                # factor.append(0)
                        else:
                            continue
                            # factor.append(None)
                except:
                    # factor.append(None)
                    continue
    # print(factor1)
    # print(factor2)
    if len(list(set(factor1 + factor2))) == 1 and list(set(factor1 + factor2))[0] == 'None':
        return u'缺失值'
    factor1 = [i for i in factor1 if i is not None and i != 'None']
    factor2 = [i for i in factor2 if i is not None and i != 'None']
    if len(factor1) != 0 or len(factor2) != 0:
        if len(factor1) == 0:
            factor1_1 = 0
            factor1_2 = 0
        else:
            factor1_1 = len([i for i in factor1 if i == 1])
            factor1_2 = max(factor1)
        if len(factor2) == 0:
            factor2_1 = 0
            factor2_2 = 0
        else:
            factor2_1 = len([i for i in factor2 if i == 3])
            factor2_2 = max(factor2)
    else:
        return 1

    if factor1_1 + factor2_1 > 3:
        return 0
    elif factor1_2 > 1 or factor2_2 > 3:
        return 0
    else:
        return 1


# if __name__ == '__main__':
#     import json
#     file_obj = open(r'C:\Users\john\Desktop\samples\case.json', 'r')
#     content = file_obj.read()
#     cQexecuteTime = ""
#     IC_DSJ_2D = json.loads(content, strict=False)['IC_DSJ_2D']
#     aa = R16_IC_AccOvduCntOfLoansAndCreditAndQuasiSixMonsCheck2()
#     print(aa)
result = R16_IC_AccOvduCntOfLoansAndCreditAndQuasiSixMonsCheck2()